package com.shenwei.yingdaoguanli.controller;

import com.shenwei.yingdaoguanli.entity.BackupLog;
import com.shenwei.yingdaoguanli.entity.FileCleanLog;
import com.shenwei.yingdaoguanli.entity.dto.BackupLogDto;
import com.shenwei.yingdaoguanli.entity.dto.FileStatDto;
import com.shenwei.yingdaoguanli.service.BackupLogService;
import com.shenwei.yingdaoguanli.service.FileCleanLogService;
import com.shenwei.yingdaoguanli.utils.FolderBackup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;

/**
 * @Author wang
 * @Date 2025/1/8 22:46
 * @PackageName:com.shenwei.yingdaoguanli.controller
 * @ClassName: FileStatController
 * @Description: TODO
 * @Version 1.0
 */
@RestController
@RequestMapping("/backupLog")
public class BackupLogController {

    @Autowired
    private BackupLogService backupLogService;

    @Value("${file.backupPath}")
    private String backupPath;
    @Value("${file.zipFilePath}")
    private String zipFilePath;

    // list
    @GetMapping("/list")
    public List<BackupLog> list(BackupLogDto bakupLogDto) {
        return backupLogService.list(bakupLogDto);
    }






    // 备份某路径下的文件 压缩为·zip文件
    @PostMapping("/backup")
    public String backup() {
        try {
            // 备份之前删除之前的备份文件
            backupLogService.deleteAll(backupPath);
            // 备份文件
            Boolean result = FolderBackup.backupFolderToZip(backupPath, zipFilePath);
            // 截取 backupPath 中的文件名
            String fileName = zipFilePath.substring(zipFilePath.lastIndexOf("/") + 1);
            if (result) {
                extracted(fileName, "成功");
                return "备份成功";
            } else {
                extracted(fileName, "失败");
                return "备份失败";
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void extracted(String fileName, String status) {
        BackupLog backupLog = new BackupLog();
        backupLog.setBackupName(fileName);
        backupLog.setBackupSize(FolderBackup.getZipSize(zipFilePath));
        String formattedTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        backupLog.setBackupTime(formattedTime);
        backupLog.setBackupStatus(status);
        backupLog.setOperator("admin");
        backupLog.setRemarks("备份文件为：BI本地数据.zip");
        backupLogService.save(backupLog);
    }

}